#!/usr/bin/env node

const https = require('https'),
      log  = console.log,
      baseurl  = 'https://ke.sifou.com',
      cheerio = require('cheerio'),
      addr = 'https://ke.sifou.com/free',
      http = require('http'),
      fs   = require('fs');

let html = fs.readFileSync('./index1.html').toString('utf-8');
let courseList = [];

https.get(addr,(res) => {
  let data = '';

  res.on('data',(chunk) => data += chunk);

  res.on('end',() => {
    let $ = cheerio.load(data);
    let courses = $('body').find('h5.card-title>a');
    let type    = $('body').find('strong.text-danger');

    for(let i=0;i<courses.length;i++){
      //log($(courses[i]).text());
      //log(baseurl + $(courses[i]).attr('href'));
      //log($(type[i]).text());
      //log();
      courseList.push({
        courseName : $(courses[i]).text(),
        courseUrl  : baseurl+$(courses[i]).attr('href'),
        courseType : $(type[1]).text()
      });
    }
    log(courseList);
  });
});

http.createServer((req,res) => {
  if(req.url === '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-Length':Buffer.byteLength(html)    
    });
    res.end(html);
  }else if(req.url === '/getlist'){
    res.statusCode = 200;
    res.setHeader('Content-Type','text/html');
    log(1);
    res.end(JSON.stringify(courseList));
  }else{
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
  }
  return;
}).listen(8080);
